package com.example.android_common.util;

import com.example.android_common.demo.MyApp;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 显示相关的工具类
 * @author hubin
 * @email 7629654@qq.com
 * @date 2014-11-07
 */
public class ShowUtils {

	/** 将dp转换成px */
	public static int dip2px(float dipValue) {
		float scale = MyApp.getInstance().getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/** px转成为dp */
	public static int px2dip(float pxValue) {
		final float scale = MyApp.getInstance().getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/** sp转成为px */  
    public static int sp2px(float spValue) {  
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,  
        		spValue, MyApp.getInstance().getResources().getDisplayMetrics());  
    }  
  
    /** px转sp */  
    public static float px2sp(float pxValue) {  
        return (pxValue / MyApp.getInstance().getResources().getDisplayMetrics().scaledDensity);  
    }  
	
	/**
	 * 精确获取屏幕尺寸（例如：3.5、4.0、5.0寸屏幕）
	 * @param ctx
	 * @return
	 */
	public static double getScreenPhysicalSize(Context ctx) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
        return diagonalPixels / (160 * dm.density);
    }
	
	/**
	 * 判断是否是平板（官方用法）
	 * @param context
	 * @return
	 */
	public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

	/**
	 * 显示Toast
	 * @param message
	 */
	private static Toast toast;
	public static void showToast(String message) {
		if (toast != null)
			toast.cancel();
		toast = Toast.makeText(MyApp.getInstance(), message, Toast.LENGTH_SHORT);
		toast.show();
	}
	/**
	 * 显示Toast
	 * @param resID
	 */
	public static void showToast(int resID) {
		if (toast != null)
			toast.cancel();
		toast = Toast.makeText(MyApp.getInstance(), resID, Toast.LENGTH_SHORT);
		toast.show();
	}
}
